﻿package _4_ListAndComboBox;

import java.awt.Color;
import java.awt.Container;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.ListModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

/**
 * 2011-6-4 23:09:11
 * 
 * @author Administrator 双击列表框中的某项可以将其删除
 */
public class TJlist {
    JFrame frame;
    Container contentPane;
    JList<String> list;
    JTextArea textArea;
    JSplitPane splitPane;

    public TJlist() {
        frame = new JFrame("JList测试");
        contentPane = frame.getContentPane();
        splitPane = new JSplitPane();
        splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);
        splitPane.setDividerSize(3);
        setList();
        splitPane.setTopComponent(new JScrollPane(list));
        setTextArea();
        splitPane.setBottomComponent(new JScrollPane(textArea));
        contentPane.add(splitPane);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    public void setList() {
        final String listArray[] = { "中国", "美国", "日本", "英国", "法国" };
        DefaultListModel<String> dlm = new DefaultListModel<String>();
        for (int i = 0; i < listArray.length; i++) {
            dlm.addElement(listArray[i]);
        }
        list = new JList<String>(dlm);
        list.setFixedCellHeight(30);
        list.setSelectionBackground(Color.green);
        list.setVisibleRowCount(10);
        list.addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
                int index[] = list.getSelectedIndices();
                StringBuffer buffer = new StringBuffer();
                buffer.append("选择的元素如下:\n");
                ListModel<String> lm = list.getModel();
                for (int i = 0; i < index.length; i++) {
                    buffer.append(lm.getElementAt(index[i]) + "\n");
                }
                textArea.setText(buffer.toString());
            }
        });
        list.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                int index = list.locationToIndex(e.getPoint());
                if (e.getClickCount() >= 2 && index != -1) {
                    DefaultListModel<String> dlm = (DefaultListModel<String>) list.getModel();
                    dlm.remove(index);
                }
            }
        });
    }

    public void setTextArea() {
        textArea = new JTextArea(10, 40);
        textArea.setEditable(false);
    }

    public static void main(String args[]) {
        new TJlist();
    }
}
